
var appConfig = {
    eleRadius: 30,//默认半径
    fill: "#a6d49e",//元素默认填充色
    space:100,
}
var linkMap = {
    1: 3,
    2: 4,
    3: 1,
    4: 2,
}
new Vue({
    el: "#page",
    data: {
        mode:'svg',
        element: [
            {
                id: +new Date(),
                cx: 500,
                cy: 300,
                r: appConfig.eleRadius,
                fill: appConfig.fill,
                bindmap: [[0,-1],[0,-1],[0,-1],[0,-1]],//连接[[id,index]]
            }
        ],
        line: [
            /*  {
                sx: 0,
                sy: 0,
                ex: 0,
                ey: 0,
                sid: 0,
                eid:0,
            } */
        ],
        freeStartEle:null,//[id,dir] 为自由链接状态
        freeStartPos:[0,0],//自由连接线起点
        freenEndPos:[0,0],//自由连接线终点
    },
    watch: {
        element: function () {
            // console.log(this.element)

            /* 自动生成连线 */
            this.autoRenderLine();
            /* 自动缓存 */
            localStorage.setItem("element",JSON.stringify(this.element))

        }
    },
    created:function(){
        var hsEle = localStorage.getItem("element");
        if(hsEle){
            this.element = JSON.parse(hsEle);
        }
    },
    mounted: function () {
        /* 新增元素 */
        App.eventBus.$on("addElement", function (payload) {
            this.mkElement(payload);
        }.bind(this))

        /* 删除元素 */
        App.eventBus.$on("elementDelete", function (id) {
            this.element = this.element.filter(function(it){
                return it.id!=id;
            })
        }.bind(this))

        /* 修改元素属性（位置等） */
        App.eventBus.$on("changeEle", function (payload) {
            this.changeEle(payload);
        }.bind(this))

        /* 开始自由链接 */
        App.eventBus.$on("freedomLinkStart", function (payload) {
            var _sp = this.getElemLinkPos(payload.scope, payload.dir-1, true);
            this.freeStartPos = [_sp[1],_sp[2]];
            this.freeStartEle = [payload.scope.id,payload.dir];
        }.bind(this))

        /* 自由链接关联元素 */
        App.eventBus.$on("linkElement", function (payload) {
            this.linkEle(this.freeStartEle,payload);
        }.bind(this))


        /* 删除连接线 */
        window.onkeydown = function(e){
            var key = e.key || e.code;
            if ((key == 'Backspace' || key == 'Delete')) {
                App.eventBus.$emit("lineDeleteCheck")
            }
        }.bind(this)
        App.eventBus.$on("lineDelete", function (payload) {
            console.log(payload)
            this.element = this.element.map(function(it){
                if(it.id==payload.sid){
                    it.bindmap[payload.s_index] = [0,-1];
                }
                if(it.id==payload.eid){
                    it.bindmap[payload.e_index] = [0,-1];
                }
                return it;
            })
        }.bind(this))

    },
    methods: {
        mouseUp: function () {
            /* 消除自由线 */
            this.freeStartEle = null;
            this.freeStartPos = [0, 0];
            this.freenEndPos = [0, 0];
            App.eventBus.$emit("mouseUp")
        },
        onCanvasMove: function (e) {
            App.eventBus.$emit("onCanvasMove", e)
            /* 自由链接状态实时修改自由先末端坐标 */
            // if(this.freeStartEle){
                this.freenEndPos = [e.offsetX,e.offsetY];
            // }
        },
        canvasClick: function () {
            App.eventBus.$emit('lineAllBlur');
        },
        /* 创建元素 */
        mkElement: function (payload) {
            /* 关联创建 */
            if (payload.dir) {
                var pos = [
                    { cx: payload.scope.cx, cy: payload.scope.cy - appConfig.space },
                    { cx: payload.scope.cx + appConfig.space, cy: payload.scope.cy },
                    { cx: payload.scope.cx, cy: payload.scope.cy + appConfig.space },
                    { cx: payload.scope.cx - appConfig.space, cy: payload.scope.cy },
                ];
                var newId = +new Date();
                var fromEle = { id: payload.scope.id, bindmap:payload.scope.bindmap };
                fromEle.bindmap[payload.dir-1] = [newId,linkMap[payload.dir]-1];
                /* 右边界 */
                var rEnd = App.canvasWidth-appConfig.eleRadius;
                /* 下边界 */
                var bEnd = App.canvasHeight-appConfig.eleRadius;
                /* 左边界 */
                var lStart = appConfig.eleRadius;
                /* 上边界 */
                var tStart = appConfig.eleRadius;
                var newEle = {
                    id: newId,
                    cx: pos[payload.dir - 1].cx>rEnd?rEnd:(pos[payload.dir - 1].cx<lStart?lStart:pos[payload.dir - 1].cx),
                    cy: pos[payload.dir - 1].cy>bEnd?bEnd:(pos[payload.dir - 1].cy<tStart?tStart:pos[payload.dir - 1].cy),
                    r: appConfig.eleRadius,
                    fill: appConfig.fill,
                    bindmap:[[0,-1],[0,-1],[0,-1],[0,-1]],
                }
                newEle.bindmap[linkMap[payload.dir]-1] = [payload.scope.id,payload.dir-1];
                this.element.push(newEle)
            }
        },
        /* 修改元素 */
        changeEle: function (payload) {
            this.element = this.element.map(function (it) {
                if (it.id == payload.id) {
                    for (var p in payload) {
                        if (payload.hasOwnProperty(p) && p != 'id') {
                            it[p] = payload[p];
                        }
                    }
                    return it;
                }
                return it;
            })
        },
        /* 关联元素
        from [id,dir]
        */
        linkEle: function (from, payload) {
            if (payload.scope.bindmap[payload.dir - 1][0] == 0 && payload.scope.id!= from[0]) {
                this.element = this.element.map(function (it) {
                    /* 来源发起元素 */
                    if (it.id == from[0]) {
                        it.bindmap[from[1] - 1] = [payload.scope.id,payload.dir-1];
                    }
                    /* 目标元素 */
                    else if (it.id == payload.scope.id) {
                        it.bindmap[payload.dir - 1] = [from[0],from[1]-1];
                    }
                    return it;
                })
            }
        },
        /* 计算连接点坐标 */
        getElemLinkPos:function(ele,linkIdIndex,self){
            if(self){
                switch(linkIdIndex){
                    case 0: return [ele.id, ele.cx, ele.cy - ele.r, 0];
                    case 1: return [ele.id, ele.cx + ele.r, ele.cy, 1];
                    case 2: return [ele.id, ele.cx, ele.cy + ele.r, 2];
                    case 3: return [ele.id, ele.cx - ele.r, ele.cy, 3];
                }
            }
            else {
                var target = this.element.filter(function (it) {
                    return it.id == ele.bindmap[linkIdIndex][0];
                })[0];
                if (!target) {
                    return false;
                }
                var rt = false;
                target.bindmap.map(function (it,index) {
                    if (it[0] == ele.id && it[1]==linkIdIndex) {
                        switch(index){
                            case 0:
                                rt = [target.id, target.cx, target.cy - target.r, 0];
                                break;
                            case 1:
                                rt = [target.id, target.cx + target.r, target.cy, 1];
                                break;
                            case 2:
                                rt = [target.id, target.cx, target.cy + target.r, 2];
                                break;
                            case 3:
                                rt = [target.id, target.cx - target.r, target.cy, 3];
                                break;
                        }
                    }
                })
                return rt;
                // }
            }
        },
        /* 根据元素数据自动生成连接线 */
        autoRenderLine: function () {
            var posObj = {};
            this.line = [];
            this.element.map(function(it){
                it.bindmap.map(function (item, index) {
                    if (item[0] > 0) {
                        /* 柄点 */
                        var bindPoint = this.getElemLinkPos(it, index, true);
                        /* 目标点 */
                        var targetPoint = this.getElemLinkPos(it, index, false);
                        /* 目标点已丢失说明元素已删除 删除柄点id*/
                        if(!targetPoint){
                            it.bindmap[index] = [0,-1];
                        }
                        else if (bindPoint && targetPoint) {
                            var cKey = [bindPoint[0], targetPoint[0]].sort().join('|') + [bindPoint[1], bindPoint[2], targetPoint[1], targetPoint[2]].sort().join('|');
                            if (!posObj[cKey]) {
                                // console.log(cKey)
                                this.line.push({
                                    sid: bindPoint[0],
                                    sx: bindPoint[1],
                                    sy: bindPoint[2],
                                    s_index:bindPoint[3],
                                    ex: targetPoint[1],
                                    ey: targetPoint[2],
                                    eid: targetPoint[0],
                                    e_index:targetPoint[3],
                                })
                                posObj[cKey] = 1;
                            }
                        }

                    }
                }.bind(this))
            }.bind(this))
            // console.log(this.element)
            // console.log(this.line)
        },
        /* 清除所有 重置 */
        clearAll(){
            if(confirm("确认要清除所有重新编辑吗？")){
                localStorage.clear();
                setTimeout(function(){
                    window.location.reload();
                })
            }
        },
        /* 模式切换 */
        changeMode:function(mode){
            this.mode = mode;
        }
    }
})